package com.effectiv.crm.modules;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.ServletContext;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class ModuleManager {
	
	@Inject
	private ApplicationContext context;
	
	@Inject
    private ServletContext servletContext;
	
	@Getter
	private List<Module> modules;
	
	@PostConstruct
	public void register() throws IOException{
		String contextPath = servletContext.getContextPath();
		log.info("Loading modules for servlet context - {}", contextPath);
		
		//scan jars for module.config
		Resource resources [] = context.getResources("classpath*:module.config");
		
		modules = new ArrayList<Module> ();
		
		for(Resource r : resources){
			
			Properties p = new Properties();
			p.load(r.getInputStream());
			
			Module m = new Module();
			
			String name = p.getProperty("name");
			
			m.setName(name);
			m.setKey(p.getProperty("key"));
			m.setUrl(contextPath + p.getProperty("url"));
			m.setVersion(p.getProperty("version"));
			
			String o = p.getProperty("order");
			
			log.info("#Module = {} , #Order = {}", name, o);
			
			m.setOrder(Integer.parseInt(o.trim()));
			
			modules.add(m);
			
			
		}
		
		Collections.sort(modules);
	}
}
